package com.ease.platform.access.service.impl;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;

import com.ease.dao.statement.factory.NamedStatementMultiFactory;
import com.ease.dao.statement.factory.XmlFreeMarkerNamedStatementFactory;
import com.ease.dao.statement.util.NamedStatementUtil;
import com.ease.platform.access.service.AbstractNamespaceJdbcTemplateAccessService;

/**
 *
 * @author nathanleewei
 *
 */
public abstract class AbstractNamespaceJdbcTemplateAccessServiceImpl extends AbstractNamespaceAccessServiceImpl implements AbstractNamespaceJdbcTemplateAccessService {

	public AbstractNamespaceJdbcTemplateAccessServiceImpl() {
		namespace = this.getClass().getSimpleName();
		init();
	}

	protected void init() {
		initNamedStatementFactory();
	}

	protected void initNamedStatementFactory() {
		this.initNamedStatementFactory(this.getClass());
	}

	protected void initNamedStatementFactory(Class<?> clazz) {

		String path = ClassUtils.classPackageAsResourcePath(clazz) + '/' + namespace + ".statement.xml";
		Resource resource = new ClassPathResource(path);
		if (resource.exists()) {
			XmlFreeMarkerNamedStatementFactory namedStatementXmlFreeMarkerFactory = new XmlFreeMarkerNamedStatementFactory();
			namedStatementXmlFreeMarkerFactory.setLocations(new Resource[] { resource });
			namedStatementXmlFreeMarkerFactory.init(namespace);

			if (null == namedStatementFactory) {
				namedStatementFactory = namedStatementXmlFreeMarkerFactory;
			} else {
				NamedStatementMultiFactory namedStatementMultiFactory = new NamedStatementMultiFactory();
				namedStatementMultiFactory.addFactory(namedStatementFactory);
				namedStatementMultiFactory.addFactory(namedStatementXmlFreeMarkerFactory);
			}
		}
	}

	private String statementName(String operation) {
		return NamedStatementUtil.statementName(namespace, operation);
	}

	protected String statement(String operation, Object parameter) {
		if (null != this.namedStatementFactory) {
			return namedStatementFactory.getNamedStatement(statementName(operation), parameter);
		}
		return null;
	}

	protected String statement(String operation) {
		return statement(operation, null);
	}

}
